package com.imooc.girl.service;

import com.imooc.girl.domain.*;

import com.imooc.girl.repository.AddGradeRepository;
import com.imooc.girl.repository.GradeInfoRepositry;
import com.imooc.girl.repository.Stu_infoRepository;
import com.imooc.girl.util.MapGradesOptions;
import com.imooc.girl.util.MapStuGrade;
import com.imooc.girl.util.ReturnResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GradeService {
    @Autowired
    private GradeInfoRepositry gradeInfoRepositry;
    @Autowired
    private AddGradeRepository addGradeRepository;
    @Autowired
    private Stu_infoRepository stu_infoRepository;

    public ReturnResult gradesService(GradesForm gradesForm)throws Exception{
        Pageable pageable = PageRequest.of(gradesForm.getCurrentPage()-1, gradesForm.getPageSize());
        Page<GetStuGrade> page = gradeInfoRepositry.findStuGradeByStuId(gradesForm.getTerm(),gradesForm.getStuClass(),gradesForm.getMajor(),gradesForm.getScoreLowerBound(),gradesForm.getScoreUpperBound(),pageable);
        List<GetStuGrade> list = page.getContent();
        Map<Object,Set<GetAddGrade>> map=new HashMap<>();
        Map<Object,Object> student=new HashMap<>();
        student.put("recordQuantity",page.getTotalElements());
        for(int i=0;i<list.size();i++){
            Set<GetAddGrade> set = new HashSet<>();
            List<GetAddGrade> add=addGradeRepository.findByAddGradesId(list.get(i).getId());
            set.addAll(add);
            map.put(list.get(i).getId(),set);
        }
        student.put("student",MapStuGrade.getStuGrade(list,map));
        return ReturnResultUtil.getSuccess(student,"成功");
    }

    public ReturnResult gradesOptionsService(GradesOptionsForm form){
        Map<Object,Object> map= new HashMap<>();
        if(null!=form.getStuClass()){
            map.put("optionsForTerm",MapGradesOptions.getGradesOptions(form.getStuClass()));
        }else if(null!=form.getMajor()) {
            Object minStuClass = stu_infoRepository.findClassByMajor(form.getMajor());
            map.put("optionsForTerm",MapGradesOptions.getGradesOptions(String.valueOf(minStuClass)));
        }else
        {
            Object minStuClass = stu_infoRepository.findClassBy();
            map.put("optionsForTerm",MapGradesOptions.getGradesOptions(String.valueOf(minStuClass)));
        }
        return ReturnResultUtil.getSuccess(map,"成功");
    }
}
